package com.web.service.impl;

import com.web.entity.HealthKnow;
import com.web.mapper.HealthKnowMapper;
import com.web.service.HealthKnowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class HealthKnowServiceImpl implements HealthKnowService {

    @Autowired
    private HealthKnowMapper healthKnowMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //增加健康知识
    @Override
    public void add(HealthKnow healthKnow) {
        redisTemplate.delete("healthKnowList");
        //设置创建时间和更新时间
        healthKnow.setCreateTime(LocalDateTime.now().toString());
        healthKnow.setUpdateTime(LocalDateTime.now().toString());
        healthKnowMapper.add(healthKnow);
    }

    //根据id查询健康知识
    @Override
    public HealthKnow findById(int id) {
        return healthKnowMapper.findById(id);
    }

    //根据id删除健康知识
    @Override
    public void deleteById(int id) {
        healthKnowMapper.deleteById(id);
    }

    //更新健康知识
    @Override
    public void update(HealthKnow healthKnow) {
        //设置更新时间
        healthKnow.setUpdateTime(LocalDateTime.now().toString());
        healthKnowMapper.update(healthKnow);
    }

    //查询所有健康知识
    @Override
    public List<HealthKnow> findAll() {

        if(!redisTemplate.hasKey("healthKnowList")){
            System.out.println("从数据库中查询");
            List<HealthKnow> healthKnowList = healthKnowMapper.findAll();
            this.redisTemplate.opsForValue().set("healthKnowList",healthKnowList);
            this.redisTemplate.expire("healthKnowList",6*60*60*1000, TimeUnit.MILLISECONDS);
            return healthKnowList;
        }

        System.out.println("从redis中查询");
        return (List<HealthKnow>) redisTemplate.opsForValue().get("healthKnowList");
    }

    @Override
    public List<HealthKnow> findByName(String name) {
          return  healthKnowMapper.findByName(name);
    }
}
